package com.enlighten.aio.friend.service.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.enlighten.aio.db.mapper.FriendMapper;
import com.enlighten.aio.db.model.Friend;
import com.enlighten.aio.db.model.FriendExample;
import com.enlighten.aio.db.model.out.FriendOut;
import com.enlighten.aio.friend.service.FriendService;
import com.x.share.mid.exception.HelperException;

@Service
public class FriendServiceImpl implements FriendService {
	@Resource
	FriendMapper friendMapper;

	@Override
	public List<FriendOut> getAllFriend(Long userId) {
		List<FriendOut> list = friendMapper.getAllFriend(userId);
		return list;
	}

	@Override
	public List<FriendOut> getAllAttentionMy(Long userId) {
		List<FriendOut> list = friendMapper.getAllAttentionMy(userId);
		return list;
	}

	@Override
	public List<FriendOut> getAllMyAttention(Long userId) {
		List<FriendOut> list = friendMapper.getAllMyAttention(userId);
		return list;
	}

	@Override
	public boolean insertFriend(Long userId, Long friendId) {
		Friend f = new Friend();
		f.setUserId(userId);
		f.setFriendId(friendId);
		f.setIsFriend(2);
		int num = friendMapper.insertSelective(f);
		if (num != 1) {
			throw new HelperException("添加失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	@Transactional
	public boolean AgreeFriendApplication(Long userId, Long friendId, Integer isFriend) {
		int num = friendMapper.updateFriend(isFriend,userId, friendId);
		if (num != 1) {
			throw new HelperException("操作失败");
		}
		Friend f = new Friend();
		f.setUserId(userId);
		f.setFriendId(friendId);
		f.setIsFriend(isFriend);
		if (isFriend == 1) {
			f.setUserId(friendId);
			f.setFriendId(userId);
			f.setIsFriend(isFriend);
			friendMapper.insertSelective(f);
		}
		return num > 0 ? true : false;
	}

	@Override
	public boolean AttentionFriend(Long userId, Long friendId) {
		Friend f = new Friend();
		f.setUserId(userId);
		f.setFriendId(friendId);
		f.setIsAttention(1);
		int num = friendMapper.updateByPrimaryKeySelective(f);
		if (num != 1) {
			throw new HelperException("关注失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	public List<Friend> getFriendAsk(Long userId) {
		FriendExample fe = new FriendExample();
		fe.or().andIsFriendEqualTo(2);
		List<Friend> list = friendMapper.selectByExample(fe);
		return list;
	}

}
